public class MergeSort {
    public static void main(String[] args) {
        int[] arr = {7, 5, 11, 2, 4, 6, 9, 1, 8, 3};
        System.out.println("排序前：");
        print(arr);

        mergeSort(arr);
        System.out.println("排序后：");
        print(arr);
    }

    private static void mergeSort(int[] ans) {
        sort(ans, 0, ans.length - 1);
    }

    private static void sort(int[] ans, int left, int right) {
        int mid = (left + right) / 2;
        if (left >= right) {
            return;
        }
        sort(ans, left, mid);
        sort(ans, mid + 1, right);
        merge(ans, left, mid, right);
    }

    private static void merge(int[] ans, int left, int mid, int right) {
        int Actr = left;
        int Bctr = mid + 1;
        int Cctr = 0;
        int lenA = mid - left + 1;
        int lenB = right - mid;
        int[] tmp = new int[right - left + 1];
        while (Actr <= mid && Bctr <= right) {
            if (ans[Actr] <= ans[Bctr]) {
                tmp[Cctr++] = ans[Actr];
                Actr++;
            } else {
                tmp[Cctr++] = ans[Bctr];
                Bctr++;
            }
        }
        while (Actr <= mid){
            tmp[Cctr ++] = ans[Actr ++];
        }
        while (Bctr <= right){
            tmp[Cctr ++] = ans[Bctr ++];
        }
        for (int i = 0; i < tmp.length; i++) {
            ans[left++] = tmp[i];
        }
    }

    public static void print(int[] arr) {
        if (arr == null) return;
        for(int i : arr) {
            System.out.print(i + " ");
        }
        System.out.println();
    }
}